#include "OgreURLPrecompiledHeader.h"

#include "OgreURLWriteFileStream.h"
#include "OgreException.h"

namespace Ogre
{

//-------------------------------------------------------------------------------------------------------------------------------------------------
URLWriteFileStream::URLWriteFileStream()
{
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
URLWriteFileStream::~URLWriteFileStream()
{
	close();
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
void URLWriteFileStream::open(const String& filename)
{
	mFile.open(filename.c_str(), std::ios_base::out | std::ios_base::binary);
	if(!mFile.is_open())
	{
		OGRE_EXCEPT( Exception::ERR_CANNOT_WRITE_TO_FILE,
			"Failed to open output stream - cannot create file '" + filename + "'.",
			"URLWriteFileStream::open" );
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
void URLWriteFileStream::close()
{
	mFile.close();
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
size_t URLWriteFileStream::writeData(void* ptr, size_t size, size_t nmemb)
{
	if(!mFile.is_open())
	{
		OGRE_EXCEPT( Exception::ERR_CANNOT_WRITE_TO_FILE,
			"Can't write data to file stream - file stream not opened.",
			"URLWriteFileStream::writeData" );
	}

	register size_t actualsize = size * nmemb;
	if(actualsize)
	{
		mFile.write((const char*)ptr, (std::streamsize)actualsize);
	}
	return actualsize;
}

} // end of namespace Ogre
